<template>
    <div class="fillContain">
        <div class="table_container">
            <el-form :inline="true" size="mini" label-width="80px" label-position="left" ref="report" :model="report">
                <el-form-item label="数据源：">
                    <el-select v-model="report.dataSourceSelect.chooseValue" style="width: 200px;" placeholder="请选择数据源"
                               filterable clearable
                               @visible-change="initDataSourceSelect">
                        <el-option
                                v-for="item in report.dataSourceSelect.options"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <textarea ref="textarea"></textarea>
            </el-form>

            <el-row v-if="hasMetaColumn" style="margin-top: 2%">
                <el-col :span="24">
                    <el-form :inline="true" label-width="120px" label-position="right">
                        <el-form-item label="报表名称：">
                            <el-input v-model="report.name" style="width: 520px;" placeholder="请输入报表名称"></el-input>
                        </el-form-item>
                        <el-form-item label="Excel标题：">
                            <el-input v-model="report.excelTitle" style="width: 520px;" placeholder="请输入导出Excel标题"></el-input>
                        </el-form-item>
                        <el-form-item label="状态：">
                            <el-select v-model="report.statusSelect.chooseValue" style="width: 200px;"
                                       placeholder="请选择状态"
                                       filterable clearable
                                       @visible-change="initStatusSelect">
                                <el-option
                                        v-for="item in report.statusSelect.options"
                                        :key="item.value"
                                        :label="item.name"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <br>
                        <el-form-item label="报表分类：">
                            <el-select v-model="report.categorySelect.chooseValue" filterable clearable
                                       placeholder="请选择报表分类"
                                       @visible-change="initCategorySelect"
                                       style="width: 200px">
                                <el-option
                                        v-for="item in report.categorySelect.options"
                                        :key="item.value"
                                        :label="item.name"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="报表数据配置：">
                            <el-select v-model="report.reportDataSelect.chooseValue" style="width: 200px;"
                                       placeholder="请选择报表数据配置"
                                       filterable clearable
                                       @visible-change="initReportDataSelect">
                                <el-option
                                        v-for="item in report.reportDataSelect.options"
                                        :key="item.value"
                                        :label="item.name"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="报表上传配置：">
                            <el-select v-model="report.reportUploadSelect.chooseValue" style="width: 200px;"
                                       placeholder="请选择报表上传配置"
                                       filterable clearable
                                       @visible-change="initReportUploadSelect">
                                <el-option
                                        v-for="item in report.reportUploadSelect.options"
                                        :key="item.value"
                                        :label="item.name"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="请选择头部模板">
                            <el-select v-model="temp.headTemp" @visible-change="getTemps" filterable clearable placeholder="请选择头部模板">
                                <el-option v-for="item in headTemps" :key="item.id" :label="item.tempName"
                                           :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="请选择尾部模板">
                            <el-select v-model="temp.endTemp" filterable clearable placeholder="请选择尾部模板">
                                <el-option v-for="item in endTemps" :key="item.id" :label="item.tempName"
                                           :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <!--参数配置-->
                        <el-form-item label="参数配置" prop="params">
                            <span v-for="(params, index) in report.params" :label=" + index">
                                <el-form :inline="true" ref="form" size="medium" label-position="left">
                                    <el-form-item label="名称:" prop="name">
                                        <el-input v-model="params.name" style="width: 120px"></el-input>
                                    </el-form-item>
                                    <el-form-item label="sql字段:" prop="sqlName">
                                        <el-input v-model="params.sqlName" style="width: 120px"></el-input>
                                    </el-form-item>
                                    <el-form-item label="类型:" prop="type">
                                         <el-select v-model="params.type" clearable placeholder="请选择"
                                                    style="width: 100px" @change="updateOptions2Value(params.type)">
                                            <el-option v-for="item in options2" :key="item.value" :label="item.label"
                                                       :value="item.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="字典编码:" prop="dataCode" v-if="params.type==3">
                                         <el-select v-model="params.value" clearable placeholder="请选择"
                                                    style="width: 100px" filterable>
                                            <el-option v-for="item in sysDict" :key="item.value"
                                                       :label="item.dictName+'('+item.dictCode+')'"
                                                       :value="item.dictCode"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="SQL编码:" prop="dataCode" v-if="params.type==4">
                                         <el-select v-model="params.value" clearable placeholder="请选择"
                                                    style="width: 100px" filterable>
                                            <el-option v-for="item in sysSQL" :key="item.value"
                                                       :label="item.sqlName+'('+item.sqlCode+')'"
                                                       :value="item.sqlCode"></el-option>
                                        </el-select>
                                    </el-form-item>

                                    <el-button @click.prevent="addparms()" size="mini" type="primary"
                                               class="el-icon-plus"></el-button>
                                    <el-button @click.prevent="removeparms(params)" size="mini" type="primary"
                                               class="el-icon-error"></el-button>
                                </el-form>
                            </span>
                        </el-form-item>

                        <!--参数配置  end-->
                        <br/>
                        <el-form-item label="表头配置：">
                            <el-input style="width:535px;" type="textarea" :autosize="{minRows:2,maxRows:6}"
                                      placeholder="请输入表头配置" v-model="headText"></el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <el-row v-if="hasMetaColumn" :gutter="20">
                <el-col :span="5"><label>列名</label></el-col>
                <el-col :span="3"><label>是否百分比</label></el-col>
                <el-col :span="3"><label>是否合并单元格</label></el-col>
                <el-col :span="3"><label>是否为可导出字段</label></el-col>
                <el-col :span="5"><label>类型转换</label></el-col>
            </el-row>
            <el-row v-if="hasMetaColumn" v-for="column in metaColumnsList" :key="column.id" :gutter="20"
                    style="margin-top: 1%">
                <el-col :span="5">
                    <el-input v-model="column.text" placeholder="请输入列名" size="mini" disabled></el-input>
                </el-col>
                <el-col :span="3">
                    <el-select v-model="column.isPercentChooseValue" size="mini" placeholder="是否百分比"
                               filterable
                               @visible-change="initIsPercentSelect">
                        <el-option
                                v-for="item in report.isPercentSelect.options"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="3">
                    <el-select v-model="column.isMergeCellValue" size="mini" placeholder="是否合并单元格"
                               filterable
                               @visible-change="initIsPercentSelect">
                        <el-option
                                v-for="item in report.isMergeCellSelect.options"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="3">
                    <el-select v-model="column.isExportChooseValue" size="mini" placeholder="是否为可导出字段"
                               filterable
                               @visible-change="initIsPercentSelect">
                        <el-option
                                v-for="item in report.isExportSelect.options"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="5">
                    <el-select v-model="column.convertTypeChooseValue" size="mini" placeholder="类型转换"
                               filterable
                               @visible-change="initConvertTypeSelect"
                               @change="changeType(column)">
                        <el-option
                                v-for="item in report.convertTypeSelect.options"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="5">
                    <el-select v-if="column.showConvertCodeDict"
                               v-model="column.convertCodeDictChooseValue" size="mini" placeholder="请输入转换码"
                               filterable
                               @visible-change="initConvertTypeSelect"
                               @change="changeType(column)">
                        <el-option
                                v-for="item in report.convertCodeDictSelect.options"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <el-select v-if="column.showConvertCodeSQL"
                               v-model="column.convertCodeSQLChooseValue" size="mini" placeholder="请输入转换码"
                               filterable
                               @visible-change="initConvertTypeSelect"
                               @change="changeType(column)">
                        <el-option
                                v-for="item in report.convertCodeSQLSelect.options"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-col>
            </el-row>

            <el-row style="margin-top: 1%">
                <el-col :span="24" style="text-align: center">
                    <el-button size="mini" round type="warning" icon="el-icon-caret-right" @click="executeSql">执行sql
                    </el-button>
                    <el-button v-if="hasMetaColumn" size="mini" round type="primary" icon="el-icon-view" @click="save">
                        保存报表
                    </el-button>
                    <el-button v-if="hasMetaColumn" size="mini" round type="primary" icon="el-icon-view"
                               @click="previewReport">
                        预览报表
                    </el-button>
                </el-col>
            </el-row>

        </div>


        <el-dialog
                title="报表预览"
                :visible.sync="dialogPreviewReport"
                width="80%">
            <el-table>
                <table-header v-bind:tableHeaderChildData="tableHeaderTreeDataCopy"></table-header>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogPreviewReport = false">取 消</el-button>
                 <el-button type="primary" @click="dialogPreviewReport = false">确 定</el-button>
             </span>
        </el-dialog>
    </div>

</template>

<script>
    /* eslint-disable no-console,no-undef */
    //import {axios} from '../utils/'
    import {execSqlText, getReoprtInfo, addReport, previewReport, updateReport} from '@/api/getData'
    import {getTempUpload} from '@/api/tempUploadLog'
    import {ListSysDictAndSQL} from '@/api/reportData'
    import HeadTop from '@/views/main-components/HeadTop.vue'
    import TableHeaderTree from '@/views/report/TableHeaderTree.vue'
    import ReportPreview from '@/views/report/ReportPreview.vue'
    import TableHeader from '@/views/report/TableHeader.vue'

    import {getStore, setStore} from '@/utils/storage';

    import CodeMirror from 'codemirror'
    import 'codemirror/addon/lint/lint.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/theme/rubyblue.css'

    import 'codemirror/mode/javascript/javascript'
    import 'codemirror/addon/lint/lint'
    import 'codemirror/addon/hint/sql-hint'

    export default {
        data() {
            return {
                report: {
                    id: '',
                    reportId: '',
                    categoryId: 1,
                    tempName: '',
                    excelTitle:'',
                    name: '',//报表名称
                    dsId: '',//数据源
                    sqlText: '',//sql语句
                    metaColumns: '',//元数据列
                    queryParams: '',//查询参数
                    options: '',//配置选项
                    status: '',//状态,
                    params: [{
                        name: '',    //字段label显示名
                        sqlName: '',  //数据库字段名
                        type: '',     //类型
                        value: ''     //选择字典或者sql表时对应的ID
                    }],
                    isMergeCellSelect: {
                        chooseValue: '',
                        options: []
                    },
                    categorySelect: {
                        chooseValue: '',
                        options: []
                    },
                    convertTypeSelect: {
                        chooseValue: '',
                        options: []
                    },
                    isPercentSelect: {
                        chooseValue: '',
                        options: []
                    },
                    isExportSelect: {
                        chooseValue: '',
                        options: []

                    },
                    dataSourceSelect: {
                        chooseValue: '',
                        options: []
                    },
                    //是否可以编辑下拉框
                    /*                    isEditSelect:{
                                            chooseValue: '',
                                            options: []
                                        },*/
                    statusSelect: {
                        chooseValue: '',
                        options: []
                    },
                    reportDataSelect: {
                        chooseValue: '',
                        options: []
                    },
                    reportUploadSelect: {
                        chooseValue: '',
                        options: []
                    },
                    //转换码下拉框
                    convertCodeSQLSelect: {
                        chooseValue: '',
                        options: []
                    },
                    convertCodeDictSelect: {
                        chooseValue: '',
                        options: []
                    }
                },
                previewReportData: {
                    comment: '',
                    formHtmlText: '',
                    id: '',
                    name: '',
                    nonStatColumHtmlText: '',
                    statColumHtmlText: '',
                    uid: ''
                },
                sqlEditor: false,
                hasMetaColumn: false,
                metaColumnsList: "",
                //tableHeaderTreeData: [],
                tableHeaderTreeDataCopy: [],
                dialogPreviewReport: false,
                //表头配置
                headText: "",
                //是新增为false, 修改为true
                isEdit: false,
                //后续新增
                options2: [{value: '1', label: '输入取值'}, {value: '2', label: '时间取值'}, {
                    value: '3',
                    label: '字典下拉'
                }, {value: '4', label: 'sql下拉'}, {value: '5', label: '账期选择'}],//参数配置类型
                sysDict: [],//字典表数据
                sysSQL: [],//syssql表数据
                headTemps: [],//头部模板集合
                endTemps: [],//尾部模板集合
                temp: {
                    headTemp: '',
                    endTemp: ''
                },
            };
        },
        created: function () {
            this.getTemps();
        },
        mounted() {
            //设置sql样式
            this.sqlEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
                mode: 'text/x-mysql',
                theme: 'rubyblue',
                indentWithTabs: true,
                smartIndent: true,
                // lineNumbers: true,
                matchBrackets: true,
                autofocus: true,
                width: '100%',
                extraKeys: {
                    "F1": function (cm) {
                        cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                    },
                    "Esc": function (cm) {
                        if (cm.getOption("fullScreen")) {
                            cm.setOption("fullScreen", false);
                        }
                    }
                }
            });
            this.initDataSourceSelect(true);
            this.initStatusSelect(true);
            this.initReportDataSelect(true);
            this.initReportUploadSelect(true);
            this.initConvertTypeSelect(true);
            this.initIsPercentSelect(true);
            this.initCategorySelect(true);
        },
        computed: {},
        components: {
            HeadTop,
            TableHeaderTree,
            ReportPreview,
            TableHeader
        },
        methods: {

            /**
             * 点击删除，删除一行参数
             * @param item
             */
            removeparms(item) {
                var index = this.report.params.indexOf(item)
                if (this.report.params.length > 1) {
                    this.report.params.splice(index, 1);
                    return;
                }
                if (this.report.params.length <= 1) {
                    this.$notify.error({
                        title: '',
                        message: '不允许删除'
                    });
                }

            },
            /**
             * 点击新增，新增一行参数
             */
            addparms() {
                this.report.params.push({
                    name: '',    //字段label显示名
                    sqlName: '',  //数据库字段名
                    type: '',     //类型
                    value: ''     //选择字典或者sql表时对应的ID
                });
            },

            /**
             * 参数配置的值发生变化
             */
            async updateOptions2Value(value) {
                this.sysDict = [];
                this.sysSQL = [];
                let list = await ListSysDictAndSQL();
                this.sysDict = list.sysdicts;
                this.sysSQL = list.syssqls;
            },

            async initConvertCodeSelect(bool, convertType) {
                //convertType转换类型
                if (bool) {
                    //字典转换
                    if (convertType == 2) {
                        //初始化 转换码下拉框
                        var categorySelect = await this.getSysSql('SYS_DICT_ITEM_DICT');
                        this.report.convertCodeDictSelect.options = categorySelect;
                    } else if (convertType == 3) {
                        //SYS_SQL转换
                        var categorySelect = await this.getSysSql('SYS_SQL_DICT');
                        this.report.convertCodeSQLSelect.options = categorySelect;
                    }
                }
            },
            async initCategorySelect(bool) {
                if (bool) {
                    //初始化 sqlCode
                    var categorySelect = await this.getSysSql('REPORT_CATEGORY_NAME');
                    this.report.categorySelect.options = categorySelect;
                }
            },
            async initConvertTypeSelect(bool) {
                if (bool) {
                    //初始化 字典菜单
                    var select = await this.getSysDictItem('CONVERT_TYPE');
                    this.report.convertTypeSelect.options = select;
                    this.report.convertTypeSelect.chooseValue = "1";
                }
            },
            async initIsPercentSelect(bool) {
                if (bool) {
                    //初始化 字典菜单
                    var select = await this.getSysDictItem('YES_NO_BOOLEAN');
                    this.report.isPercentSelect.options = select;
                    this.report.isPercentSelect.chooseValue = "false";
                    this.report.isMergeCellSelect.options = select;
                    this.report.isMergeCellSelect.chooseValue = "false";
                    this.report.isExportSelect.options = select;
                    this.report.isExportSelect.chooseValue = "true";
                }
            },
            async initDataSourceSelect(bool) {
                if (bool) {
                    //初始化 sqlCode
                    var categorySelect = await this.getSysSql('DATASOURCE_NAME');
                    this.report.dataSourceSelect.options = categorySelect;
                }
            },
            async initStatusSelect(bool) {
                if (bool) {
                    //初始化 状态下拉框
                    var result = await this.getSysDictItem('REPORT_STATUS');
                    this.report.statusSelect.options = result;
                }
            },
            async initReportDataSelect(bool) {
                if (bool) {
                    //初始化 报表数据配置下拉框
                    var categorySelect = await this.getSysSql('REPORT_DATA_DICT');
                    var status = {
                        name: '不生成',
                        value: -1
                    }
                    categorySelect.unshift(status);
                    this.report.reportDataSelect.options = categorySelect;
                }
            },
            async initReportUploadSelect(bool) {
                if (bool) {
                    //初始化 报表上传配置下拉框
                    var result = await this.getSysSql('REPORT_UPLOAD_DICT');
                    this.report.reportUploadSelect.options = result;
                }
            },
            //查询报表
            async query() {
                let reply = await getReoprtInfo();
                if (reply == undefined || reply == 'error') {
                    this.$notify.error({
                        title: '错误',
                        message: '服务器异常或无响应，请联系相关人员！'
                    });
                }
            },
            //执行sql
            async executeSql() {
                if (this.sqlEditor.getValue() == ""
                    || this.sqlEditor.getValue() == null
                    || this.sqlEditor.getValue() == undefined) {
                    this.$message.error('请输入sql语句后，再执行sql');
                    return;
                }
                if (this.report.dataSourceSelect.chooseValue == ""
                    || this.report.dataSourceSelect.chooseValue == null
                    || this.report.dataSourceSelect.chooseValue == undefined) {
                    this.$message.error('请选择数据源后，再执行sql');
                    return;
                }
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                let param = {
                    sqlText: this.sqlEditor.getValue(),
                    dsId: this.report.dataSourceSelect.chooseValue,
                    dataRange: '',
                    queryParams: null
                };
                this.report.sqlText = this.sqlEditor.getValue();
                let reply = await execSqlText(param);
                loading.close();
                if (reply.code == 500) {
                    this.$notify.error({
                        title: '错误',
                        message: '服务器异常或sql有误请先检查sql无误后，再联系相关人员！'
                    });
                } else {
                    this.hasMetaColumn = true;
                    //如果是新增清空表单内容
                    if (!this.isEdit) {
                        this.report.id = '';
                        this.report.name = '';
                        this.report.excelTitle = '';
                        this.temp.headTemp = '';
                        this.temp.endTemp = '';
                        this.report.statusSelect.chooseValue = '';
                        this.report.categorySelect.chooseValue = '';
                        this.report.reportDataSelect.chooseValue = '';
                        this.report.reportUploadSelect.chooseValue = '';
                        this.headText = '';
                        this.metaColumnsList = [];
                    }
                    //初始化其余配置
                    for (var i = 0; i < reply.data.length; i++) {
                        reply.data[i].showConvertCodeDict = false;
                        reply.data[i].showConvertCodeSQL = false;
                        reply.data[i].convertTypeChooseValue = "1";
                        reply.data[i].isPercentChooseValue = "false";
                        reply.data[i].isMergeCellValue = "false";
                        reply.data[i].isExportChooseValue = "true";
                        //reply.data[i].isEditValue = "false";//是否可以编辑
                        reply.data[i].convertCodeDictChooseValue = '';
                        reply.data[i].convertCodeSQLChooseValue = '';
                    }
                    if (this.metaColumnsList.length < 1) {
                        this.metaColumnsList = reply.data;
                    } else {
                        //如果列表中存在旧的列则需要替换相同的列并增加新列
                        var oldRowMap = {};
                        for (let i = 0; i < this.metaColumnsList.length; i++) {
                            var name = this.metaColumnsList[i].name;
                            oldRowMap[name] = this.metaColumnsList[i];
                        }

                        for (let i = 0; i < reply.data.length; i++) {
                            let name = reply.data[i].name;
                            if (oldRowMap[name]) {
                                oldRowMap[name].dataType = reply.data[i].dataType;
                                oldRowMap[name].width = reply.data[i].width;
                                //表头宽度默认为0
                                reply.data[i] = oldRowMap[name];
                            }
                        }
                        this.metaColumnsList = reply.data;
                    }
                }

            },
            previewReport() {
                //校验表单内容
                if (!this.validForm()) {
                    return;
                }
                //获取表头配置json
                var headText = this.headText;
                var resultStr = headText.replace(/\ +/g, "");//去掉空格
                resultStr = headText.replace(/[ ]/g, "");    //去掉空格
                resultStr = headText.replace(/[\r\n]/g, "");//去掉回车换行
                var arry = resultStr.split(";");
                for (var i = 0; i < arry.length; i++) {
                    if (arry[i] == null || arry[i] == "" || arry[i] == undefined) {
                        arry.splice(i, 1);
                        i--;
                    }
                }
                var header = JSON.stringify(arry);
                //获取字段配置json
                var arrys = new Array();
                for (var i = 0; i < this.metaColumnsList.length; i++) {
                    var name = this.metaColumnsList[i].text;
                    var convertType = this.metaColumnsList[i].convertTypeChooseValue;
                    var isPercent = this.metaColumnsList[i].isPercentChooseValue;
                    var isMergeCell = this.metaColumnsList[i].isMergeCellValue;
                    var isExport = this.metaColumnsList[i].isExportChooseValue;
                    var isEdit = this.metaColumnsList[i].isEditValue;
                    var convertValue = '';
                    if (convertType == 1) {
                        convertValue = '';
                    } else if (convertType == 2) {
                        convertValue = this.metaColumnsList[i].convertCodeDictChooseValue;
                    } else if (convertType == 3) {
                        convertValue = this.metaColumnsList[i].convertCodeSQLChooseValue;
                    }
                    var param = {
                        name: name,
                        convertType: convertType,
                        convertValue: convertValue,
                        isPercent: isPercent,
                        isMergeCell: isMergeCell,
                        isEdit: isEdit,
                        isExport:isExport
                    }
                    arrys.push(param);
                }
                var meta_columns = JSON.stringify(arrys);
                var params = {
                    id: this.report.id,
                    name: this.report.name,
                    excelTitle : this.report.excelTitle,
                    categoryId: this.report.categorySelect.chooseValue,
                    dsId: this.report.dataSourceSelect.chooseValue,
                    sqlText: this.sqlEditor.getValue(),
                    header: header,
                    metaColumns: meta_columns,
                    reportDataId: this.report.reportDataSelect.chooseValue,
                    reportUploadId: this.report.reportUploadSelect.chooseValue,
                    status: this.report.statusSelect.chooseValue,
                    viewParams: this.report.params
                }
                this.$emit('previewReport', params);
            },
            async save() {
                //校验表单内容
                if (!this.validForm()) {
                    return;
                }
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                this.report.options = JSON.stringify({
                        layout: this.report.layout,
                        statColumnLayout: this.report.statColumnLayout
                    }
                );
                //let metaColumnStr = JSON.stringify(this.metaColumnsList);
                //获取表头配置json
                var headText = this.headText;
                var resultStr = headText.replace(/\ +/g, "");//去掉空格
                resultStr = headText.replace(/[ ]/g, "");    //去掉空格
                resultStr = headText.replace(/[\r\n]/g, "");//去掉回车换行
                var arry = resultStr.split(";");
                for (var i = 0; i < arry.length; i++) {
                    if (arry[i] == null || arry[i] == "" || arry[i] == undefined) {
                        arry.splice(i, 1);
                        i--;
                    }
                }
                var header = JSON.stringify(arry)
                //获取字段配置json
                var arrys = new Array();
                for (var i = 0; i < this.metaColumnsList.length; i++) {
                    var name = this.metaColumnsList[i].text;
                    var convertType = this.metaColumnsList[i].convertTypeChooseValue;
                    var isPercent = this.metaColumnsList[i].isPercentChooseValue;
                    var isMergeCell = this.metaColumnsList[i].isMergeCellValue;
                    var isExport = this.metaColumnsList[i].isExportChooseValue;
                    var isEdit = this.metaColumnsList[i].isEditValue;
                    var convertValue = '';
                    if (convertType == 1) {
                        convertValue = '';
                    } else if (convertType == 2) {
                        convertValue = this.metaColumnsList[i].convertCodeDictChooseValue;
                    } else if (convertType == 3) {
                        convertValue = this.metaColumnsList[i].convertCodeSQLChooseValue;
                    }
                    var param = {
                        name: name,
                        convertType: convertType,
                        convertValue: convertValue,
                        isPercent: isPercent,
                        isMergeCell: isMergeCell,
                        isExport: isExport,
                        isEdit: isEdit
                    }
                    arrys.push(param);
                }
                var meta_columns = JSON.stringify(arrys);
                var params = {
                    id: this.report.reportId,
                    name: this.report.name,
                    excelTitle: this.report.excelTitle,
                    categoryId: this.report.categorySelect.chooseValue,
                    dsId: this.report.dataSourceSelect.chooseValue,
                    headTemp: this.temp.headTemp,
                    endTemp: this.temp.endTemp,
                    sqlText: this.sqlEditor.getValue(),
                    header: header,
                    metaColumns: meta_columns,
                    reportDataId: this.report.reportDataSelect.chooseValue,
                    reportUploadId: this.report.reportUploadSelect.chooseValue,
                    status: this.report.statusSelect.chooseValue,
                    params: JSON.stringify(this.report.params)
                }
                let reply = this.isEdit ? await updateReport(params) : await addReport(params);
                if (reply.code == 200) {
                    this.report.id = reply.data;
                    loading.close();
                    this.$notify.success({
                        title: '',
                        message: '成功！'
                    });
                    this.$emit('closePop');
                } else {
                    this.$notify.error({
                        title: '失败！',
                        message: reply.msg
                    });
                    loading.close();
                }
            },

            test: function () {
            },
            handleDrop(draggingNode, dropNode, dropType, ev) {
                this.$store.commit('saveTableHeader', this.tableHeaderTreeData);
            },
            //初始化报表配置
            async initMethod(params) {
                this.clearForm();
                this.report.reportId = params.id;
                this.isEdit = params.isEdit;
                this.report.dataSourceSelect.chooseValue = params.dataSourceValue;
                this.sqlEditor.setValue(params.sqlText);
                //确认是否编辑，如果是编辑的话需要将字段配置查询出来
                if (params.isEdit) {
                    await this.executeSql();
                    this.report.statusSelect.chooseValue = params.statusValue;
                    this.report.reportDataSelect.chooseValue = params.reportDataValue;
                    this.report.reportUploadSelect.chooseValue = params.reportUploadValue;
                    this.report.categorySelect.chooseValue = params.categoryId;
                    this.report.name = params.name;
                    this.report.excelTitle = params.excelTitle;
                    this.temp.headTemp = params.headTemp;
                    this.temp.endTemp = params.endTemp;
                    this.report.params = params.params;
                    //转换表头
                    var head = JSON.parse(params.header);
                    var text = "";
                    for (var i = 0; i < head.length; i++) {
                        text += (head[i] + ";\r\n");
                    }
                    this.headText = text;
                    //转换字段选项配置
                    var obj = JSON.parse(params.metaColumns);
                    for (var i = 0; i < this.metaColumnsList.length; i++) {
                        var name = this.metaColumnsList[i].name;
                        for (var o = 0; o < obj.length; o++) {
                            if (name.toLowerCase() == obj[o].name.toLowerCase()) {
                                this.metaColumnsList[i].showConvertCode = false;
                                this.metaColumnsList[i].convertTypeChooseValue = obj[i].convertType;
                                if (this.metaColumnsList[i].convertTypeChooseValue == 1) {
                                    this.metaColumnsList[i].showConvertCodeDict = false;
                                    this.metaColumnsList[i].showConvertCodeSQL = false;
                                } else if (this.metaColumnsList[i].convertTypeChooseValue == 2) {
                                    //初始化加载 转换码下拉框
                                    await this.initConvertCodeSelect(true, this.metaColumnsList[i].convertTypeChooseValue);
                                    this.metaColumnsList[i].showConvertCodeDict = true;
                                    this.metaColumnsList[i].showConvertCodeSQL = false;
                                } else if (this.metaColumnsList[i].convertTypeChooseValue == 3) {
                                    await this.initConvertCodeSelect(true, this.metaColumnsList[i].convertTypeChooseValue);
                                    this.metaColumnsList[i].showConvertCodeDict = false;
                                    this.metaColumnsList[i].showConvertCodeSQL = true;
                                }
                                if (this.metaColumnsList[i].showConvertCodeDict
                                    || this.metaColumnsList[i].showConvertCodeSQL) {
                                    await this.initConvertCodeSelect(true, obj[i].convertType);
                                    //字典下拉框
                                    if (obj[i].convertType == 2) {
                                        this.metaColumnsList[i].convertCodeDictChooseValue = obj[i].convertValue;
                                    } else if (obj[i].convertType == 3) {
                                        //SQL下拉框
                                        this.metaColumnsList[i].convertCodeSQLChooseValue = obj[i].convertValue;
                                    }
                                }
                                this.metaColumnsList[i].isPercentChooseValue = obj[i].isPercent;
                                this.metaColumnsList[i].isMergeCellValue = obj[i].isMergeCell;
                                this.metaColumnsList[i].isExportChooseValue = obj[i].isExport;
                                break;
                            }
                        }
                    }
                } else {
                    this.report.sqlText = params.sqlText;
                    this.hasMetaColumn = false;
                }
                //刷新
                await this.$nextTick(function () {
                    this.sqlEditor.refresh();
                });
            },
            /**
             * 清空表单
             * */
            clearForm() {
                this.report.id = '';
                this.report.name = '';
                this.report.excelTitle = '';
                this.temp.headTemp = '';
                this.temp.endTemp = '';
                this.report.statusSelect.chooseValue = '';
                this.report.categorySelect.chooseValue = '';
                this.report.reportDataSelect.chooseValue = '';
                this.report.reportUploadSelect.chooseValue = '';
                this.report.isExportSelect.chooseValue = '';
                this.headText = '';
                this.metaColumnsList = [];
                this.report.params = [{name: '', sqlName: '', type: '', value: ''}];
                this.report.titleShow = {title: "", sec_title: "", root_title: "", root_sec_title: ""};
                this.report.payBusinessCode = "";
                this.report.payBusinessShow = false;
                this.report.isBillingCycleTable = false;
            },
            //每行的类型转换变化时调用
            async changeType(row) {
                if (row.convertTypeChooseValue == 1) {
                    row.showConvertCodeDict = false;
                    row.showConvertCodeSQL = false;
                } else if (row.convertTypeChooseValue == 2) {
                    //初始化加载 转换码下拉框
                    await this.initConvertCodeSelect(true, row.convertTypeChooseValue);
                    row.showConvertCodeDict = true;
                    row.showConvertCodeSQL = false;
                } else if (row.convertTypeChooseValue == 3) {
                    await this.initConvertCodeSelect(true, row.convertTypeChooseValue);
                    row.showConvertCodeDict = false;
                    row.showConvertCodeSQL = true;
                }
            },
            //表单校验
            validForm() {
                var bool = true;
                if (this.report.dataSourceSelect.chooseValue == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '数据源不能为空！'
                    });
                    bool = false;
                }
                if (this.report.name == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '报表名称不能为空！'
                    });
                    bool = false;
                }
                if (this.report.excelTitle == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: 'excel标题不能为空！'
                    });
                    bool = false;
                }
                if (this.report.statusSelect.chooseValue == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '请选择状态！'
                    });
                    bool = false;
                }
                if (this.report.categorySelect.chooseValue == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '请选择报表分类！'
                    });
                    bool = false;
                }
                if (this.report.reportDataSelect.chooseValue == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '请选择报表数据配置！'
                    });
                    bool = false;
                }
                if (this.report.reportUploadSelect.chooseValue == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '请选择报表上传配置！'
                    });
                    bool = false;
                }
                if (this.headText == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '表头配置不能为空！'
                    });
                    bool = false;
                }
                if (this.temp.headTemp == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '头部模板不能为空！'
                    });
                    bool = false;
                }
                if (this.temp.endTemp == "") {
                    this.$notify.warning({
                        title: '提示',
                        message: '尾部模板不能为空！'
                    });
                    bool = false;
                }
                return bool;
            },
            //获取头部模板和尾部模板
            async getTemps() {
                let headParams = {
                    size: 100000,
                    current: 1,
                    tempType: "0"
                }
                let endParams = {
                    size: 100000,
                    current: 1,
                    tempType: "1"
                }
                let headReply = await getTempUpload(headParams);
                let endReply = await getTempUpload(endParams);
                this.headTemps = headReply.data.list;
                this.endTemps = endReply.data.list;
            },
        }
    }
</script>

<style scoped>

</style>